﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Mvc;

namespace Solidinfo.Web.Helpers
{
    public class SolidinfoAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
    {
        public ICollection<string> AccessItems { get; private set; }
        public SolidinfoAuthorizeAttribute(params string[] acccessItems)
        {
            AccessItems = acccessItems;
        }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var userPrincipal = filterContext.HttpContext.User as MyFormsPrincipal<UserData>;
            if (userPrincipal == null)
            {
                filterContext.Result = new RedirectToRouteResult(filterContext.RouteData.Values);
            }
            else
            {
                foreach (var item in AccessItems)
                {
                    if (userPrincipal.IsInRole(item))
                    {
                        return;
                    }
                }
                filterContext.Result = new ContentResult()
                {
                    Content = "您无权限访问该页"
                };// new EmptyResult();
            }
        }

        public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
        {
            throw new NotImplementedException();
        }
    }
}